package com.weifly.weistock.web.frame;

import com.weifly.weistock.core.common.ErrorCode;
import com.weifly.weistock.core.common.Result;
import com.weifly.weistock.core.common.StockException;
import com.weifly.weistock.core.util.WeistockUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 处理异常
 *
 * @author weifly
 * @since 2021/1/8
 */
public class WeistockHandlerExceptionResolver implements HandlerExceptionResolver {

    private Logger log = LoggerFactory.getLogger(WeistockHandlerExceptionResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        log.error("捕获未处理异常", ex);
        Result result = new Result();
        if (ex instanceof StockException) {
            result.setCode(((StockException) ex).getCode());
            result.setMessage(ex.getMessage());
        } else {
            result.setCode(ErrorCode.RESULT_SYS_ERROR);
            result.setMessage(ex.toString());
            result.setData(buildStackMessage(ex));
        }

        try {
            response.getWriter().write(WeistockUtils.toJsonString(result));
        } catch (IOException e) {
            // 忽略
        }

        return new ModelAndView();
    }

    private List<String> buildStackMessage(Exception ex) {
        List<String> stackList = new ArrayList<>();
        stackList.add(ex.toString());
        for (StackTraceElement stackTraceElement : ex.getStackTrace()) {
            stackList.add(stackTraceElement.toString());
        }
        return stackList;
    }
}
